package cn.xiaoliu.hrm.exceptionhandle;

import cn.xiaoliu.hrm.constant.GlobalStatusCode;
import cn.xiaoliu.hrm.util.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice //基于aop的全局异常处理  相当于在controller有了切面
public class GlobalExceptionHandle {

  /*  @ExceptionHandler(value = RuntimeException.class)
    public AjaxResult handleException(@RequestBody RuntimeException e){
        return AjaxResult.me().setSuccess(false).setMessage("异常信息："+e.getMessage()).setCode(GlobalStatusCode.GLOBAL_EXCEPTION_ERROR.getCode());
    }*/
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult methodArgsException(@RequestBody MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        HashMap<String, Object> map = new HashMap<>();
        fieldErrors.stream().forEach(fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage() );
        });
        return AjaxResult.me().setSuccess(false).setMessage(map.toString()).setCode(HttpStatus.BAD_REQUEST.value());
    }
}
